"""
连续时间验证器
避免瞬时信号误触发，要求连续多分钟满足条件
"""
import logging
from ..base import SignalValidator, ValidationContext, ValidationResult

logger = logging.getLogger('ConsecutiveTimeValidator')


class ConsecutiveTimeValidator(SignalValidator):
    """
    连续时间验证器
    要求: 在最近lookback_minutes分钟内，有超过threshold比例的时间满足卖出条件
    """
    
    def __init__(self, lookback_minutes: int = 3, threshold: float = 0.5):
        """
        Args:
            lookback_minutes: 回看分钟数
            threshold: 满足条件的最低比例（0-1）
        """
        self.lookback_minutes = lookback_minutes
        self.threshold = threshold
    
    def validate(self, context: ValidationContext) -> ValidationResult:
        """验证连续时间条件"""
        if context.current_index < 1:
            # 数据不足，放宽要求
            return ValidationResult(
                passed=True,
                validator_name=self.get_name(),
                details="数据不足，跳过验证",
                confidence=0.5
            )
        
        satisfied_count = 0
        total_minutes = min(self.lookback_minutes, context.current_index + 1)
        
        # 检查最近N分钟内满足条件的次数
        for i in range(context.current_index - total_minutes + 1, context.current_index + 1):
            if self._check_basic_sell_conditions(context.stock_data, i):
                satisfied_count += 1
        
        ratio = satisfied_count / total_minutes
        passed = ratio >= self.threshold
        
        return ValidationResult(
            passed=passed,
            validator_name=self.get_name(),
            details=f"{satisfied_count}/{total_minutes}分钟满足条件 (阈值:{self.threshold:.0%})",
            confidence=ratio
        )
    
    def get_name(self) -> str:
        return "连续时间确认"

